package com.boguan.device.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.boguan.common.annotation.DataScope;
import com.boguan.common.config.ProjectConfig;
import com.boguan.common.constant.UserConstants;
import com.boguan.common.core.domain.entity.SysUser;
import com.boguan.common.core.domain.model.LoginUser;
import com.boguan.common.exception.CustomException;
import com.boguan.common.utils.SMSVerification;
import com.boguan.common.utils.SecurityUtils;
import com.boguan.common.utils.ServletUtils;
import com.boguan.common.utils.StringUtils;
import com.boguan.common.utils.http.HttpUtils;
import com.boguan.device.domain.*;
import com.boguan.device.domain.dto.AddGroupDto;
import com.boguan.device.domain.dto.AlarmHistoryDto;
import com.boguan.device.domain.dto.DeviceInfoDto;
import com.boguan.device.domain.dto.DeviceSearchDto;
import com.boguan.device.domain.vo.*;
import com.boguan.device.mapper.*;
import com.boguan.device.service.IDeviceService;
import com.boguan.device.weiyu.WeiYuDeviceUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import com.boguan.framework.web.service.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeviceServiceImpl implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceTypeParamMapper deviceTypeParamMapper;

    @Autowired
    private DeviceParamMapper deviceParamMapper;

    @Autowired
    private DeviceAlarmInformMapper deviceAlarmInformMapper;

    @Autowired
    private DevicePastRecordsMapper devicePastRecordsMapper;

    @Autowired
    private DeviceLogMapper deviceLogMapper;

    @Autowired
    private DeviceAlarmLogMapper deviceAlarmLogMapper;

    @Autowired
    private SMSVerification smsVerification;

    @Autowired
    private TokenService tokenService;



    @Override
    public List<Device> selectDeviceByTypeId(Long typeId) {
        return deviceMapper.selectDeviceByTypeId(typeId);
    }

    @Override
    public Device selectDeviceByDeviceId(Long deviceId) {
        return deviceMapper.selectByPrimaryKey(deviceId);
    }

    @Override
    public String checkDeviceNumUnique(Device device) {
        Device checkDeviceNum = deviceMapper.checkDeviceByDeviceNum(device);
        if (StringUtils.isNotNull(checkDeviceNum) && !checkDeviceNum.getDeviceId().equals(device.getDeviceId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int createDevice(Device device) {

        return deviceMapper.insertSelective(device);
    }

    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateByPrimaryKeySelective(device);
    }

    @Override
    @DataScope(deptAlias = "sd")
    public List<Device> searchPage(Device device) {
        return deviceMapper.searchPage(device);
    }

    @Override
    @Transactional
    public int deleteDevice(Long deviceId) {
        Device device = selectDeviceByDeviceId(deviceId);
        int i = deviceMapper.deleteByPrimaryKey(deviceId);
        if (i > 0 && device.getAddr() != 0) {
            Device parentDevice = selectDeviceByDeviceId(device.getParentId());
            parentDevice.setChildNumber(parentDevice.getChildNumber() - 1);
            updateDevice(parentDevice);
        }
        deviceParamMapper.deleteByDeviceId(deviceId);
        devicePastRecordsMapper.deleteByDeviceId(deviceId);
        deviceAlarmInformMapper.deleteByDeviceId(deviceId);
        deviceAlarmLogMapper.deleteByDeviceId(deviceId);
        return i;
    }

    @Override
    public DeviceParamVo selectDeviceParam(Long deviceId, Integer paramType) {
        return deviceMapper.selectParamVoByParamTypeAndDeviceId(paramType, deviceId);
    }

    @Override
    @Transactional
    public int setDeviceParam(DeviceParamVo deviceParamVo) {
        Device device = selectDeviceByDeviceId(deviceParamVo.getDeviceId());
        //删除原来的参数配置信息
        deviceParamMapper.deleteByDeviceIdAndParamType(deviceParamVo.getDeviceId(), 3);
        List<DeviceParam> deviceParams = deviceParamVo.getDeviceParams();
        int code = 0;
        for (DeviceParam deviceParam : deviceParams) {
            deviceParam.setDeviceId(device.getDeviceId());
            deviceParam.setTypeId(device.getTypeId());
            Integer dataType = deviceParam.getDataType();
            //1数值 ，2枚举,3字符串，4浮点数
            try {
                switch (dataType) {
                    case 1:
                        Integer.parseInt(deviceParam.getValue());
                        break;
                    case 4:
                        Double.parseDouble(deviceParam.getValue());
                        break;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                throw new CustomException("参数数据格式错误，请重新填写");
            }
            code = deviceParamMapper.insertSelective(deviceParam);
        }
        return code;
    }

    @Override
    public List<DeviceAlarmInform> selectDeviceAlarmConfig(Long deviceId) {
        return deviceAlarmInformMapper.selectByDeviceId(deviceId);
    }

    @Override
    public int addDeviceAlarmConfig(DeviceAlarmInform deviceAlarmInform) {
        deviceAlarmInform.setCreateTime(new Date());
        deviceAlarmInform.setCreateUsername(SecurityUtils.getUsername());
        return deviceAlarmInformMapper.insertSelective(deviceAlarmInform);
    }

    @Override
    public int updateDeviceAlarmConfig(DeviceAlarmInform deviceAlarmInform) {
        deviceAlarmInform.setUpdateTime(new Date());
        deviceAlarmInform.setUpdateUsername(SecurityUtils.getUsername());
        return deviceAlarmInformMapper.updateByPrimaryKeySelective(deviceAlarmInform);
    }

    @Override
    public int deleteDeviceAlarmConfig(Long id) {
        return deviceAlarmInformMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Map<String, Object> selectHistoryData(Long deviceId, Date startTime, Date endTime, Integer pageNum, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        //查询出属性值
        Device device = selectDeviceByDeviceId(deviceId);
        if (StringUtils.isNull(device)) {
            throw new CustomException("设备信息不存在");
        }
        List<DevicePastRecordsVo> devicePastRecordsVos = null;
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
            devicePastRecordsVos = devicePastRecordsMapper.selectHistoryDataTime(deviceId, startTime, endTime);
            PageInfo pageInfo = new PageInfo(devicePastRecordsVos);
            result.put("total", pageInfo.getTotal());
        } else {
            devicePastRecordsVos = devicePastRecordsMapper.selectHistoryDataTime(deviceId, startTime, endTime);
        }

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        List<Map<String, Object>> resultList = new ArrayList<>();
//        List<DeviceParam> deviceParams = device.getDeviceParams();
//        DeviceParam param = new DeviceParam();
//        param.setParamName("时间");
//        final String uuid = UUID.randomUUID().toString().substring(0, 6);
//        param.setIdentifier("dataTime" + uuid);
//        List<DeviceParam> headerList = new ArrayList<>();
//        headerList.add(param);
//        headerList.addAll(deviceParams);
//        for (DevicePastRecordsVo devicePastRecordsVo : devicePastRecordsVos) {
//            Map<String, Object> resultMap = new HashMap<>();
//            resultMap.put("dataTime" + uuid, sdf.format(devicePastRecordsVo.getTime()));
//            for (DeviceParam deviceParam : deviceParams) {
//                List<DevicePastRecords> data = devicePastRecordsVo.getDevicePastRecords();
//                String identifier = deviceParam.getIdentifier();
//                Long paramId = deviceParam.getParamId();
//                resultMap.put(identifier, "");
//                for (DevicePastRecords datum : data) {
//                    if (paramId.equals(datum.getParamId())) {
//                        resultMap.put(identifier, datum.getValue());
//                    }
//                }
//            }
//            resultList.add(resultMap);
//        }
//        deviceParams.add(param);
//        //进行排序
//        resultList.sort((o1, o2) -> {
//            String date1 = (String) o1.get("dataTime" + uuid);
//            String date2 = (String) o2.get("dataTime" + uuid);
//
//            try {
//                if (sdf.parse(date1).getTime() > sdf.parse(date2).getTime()) {
//                    return -1;
//                } else if (sdf.parse(date1).getTime() < sdf.parse(date2).getTime()) {
//                    return 1;
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            return 0;
//        });
//
//        result.put("header", headerList);
        result.put("data", devicePastRecordsVos);

        return result;
    }

    @Override
    public List<ChartVo> historyDataChart(Long deviceId, Date startTime, Date endTime) {
        List<ChartVo> devicePastRecords = devicePastRecordsMapper.historyDataChart(deviceId, startTime, endTime);
//        String attribute = "";
//        String attributeName = "";
//        Map<String, Object> dataMap = new HashMap<>();
//        List<DevicePastRecords> dataList = new ArrayList<>();
//        for (DevicePastRecords devicePastRecord : devicePastRecords) {
//            String format = devicePastRecord.getIdentifier();
//            if (attribute.equals("")) {
//                attribute = format;
//                attributeName = devicePastRecord.getParamName();
//            } else if (!attribute.equals(format)) {
//                attribute = format;
//                attributeName = devicePastRecord.getParamName();
//                dataList = new ArrayList<>();
//            }
//            dataList.add(devicePastRecord);
//            dataMap.put(attribute, dataList);
//            dataMap.put(attribute + "Name", attributeName);
//        }
//        List<Map<String, Object>> resultList = new ArrayList<>();
//        for (String key : dataMap.keySet()) {
//            Map<String, Object> resultMap = new HashMap<>();
//            if (!key.endsWith("Name")) {
//                resultMap.put("attribute", key);
//                resultMap.put("attributeName", dataMap.get(key + "Name"));
//                resultMap.put("params", dataMap.get(key));
//                resultList.add(resultMap);
//            }
//        }
        return devicePastRecords;
    }

    @Override
    public int onlineOrOffline(JSONObject jsonObject) {
        String clientid = jsonObject.getString("clientid");
        String event = jsonObject.getString("event");
        String username = jsonObject.getString("username");
        Date date = new Date();
        //查询设备信息
        Device device = deviceMapper.selectByDeviceNum(clientid, 0);
        DeviceLog deviceLog = new DeviceLog();

        deviceLog.setLogTime(date);
        deviceLog.setContent(jsonObject.toJSONString());
        if (StringUtils.isNotNull(device)) {
            deviceLog.setDeviceId(device.getDeviceId());
            if ("client.disconnected".equals(event)) {
                //设备掉线
                device.setOnlineStatus(2);
                deviceLog.setType(3);
                if (device.getAlarmFlag()) {
                    DeviceAlarmLog deviceAlarmLogs = new DeviceAlarmLog();
                    deviceAlarmLogs.setDeviceId(device.getDeviceId());
                    deviceAlarmLogs.setAlarmTime(date);
                    deviceAlarmLogs.setAlarmLevel(4);//故障
                    deviceAlarmLogs.setErrorState(1);//报警状态
                    deviceAlarmLogs.setAlarmCause("设备离线");
                    deviceAlarmLogs.setIdentifier(device.getDeviceNum() + "offline");
                    deviceAlarmLogs.setParamName("设备离线");
                    deviceAlarmLogs.setValue("");
                    deviceAlarmLogs.setStatus(1);//处理状态
                    deviceAlarmLogs.setAlarmLocation(device.getLocaltion());
                    deviceAlarmLogs.setCreateTime(date);
                    deviceAlarmLogMapper.insertSelective(deviceAlarmLogs);
                    //短息推送
                    List<DeviceAlarmInform> deviceAlarmInforms = selectDeviceAlarmConfig(device.getDeviceId());
                    if (StringUtils.isNotNull(deviceAlarmInforms)) {
                        for (DeviceAlarmInform deviceAlarmInform : deviceAlarmInforms) {
                            smsVerification.sendAlarm("及时星",
                                    deviceAlarmInform.getPhonenumber(),
                                    "SMS_210060127",
                                    "{\"deviceNum\":\"" + device.getDeviceNum() + "\",\"deviceName\":\"" + device.getDeviceName() + "\",\"name\":\"" + "'" + deviceAlarmInform.getUsername() + "'" + "\",\"msg\":\"" + deviceAlarmLogs.getAlarmCause() + "" + "\"}");
                        }
                    }
                }
            } else if ("client.connected".equals(event)) {
                //设备上线
                device.setOnlineStatus(1);
                deviceLog.setType(2);
                DeviceAlarmLog deviceAlarmLog = deviceAlarmLogMapper.selectAlarmByError(device.getDeviceId(), device.getDeviceNum() + "offline", 1, 1);
                if (StringUtils.isNotNull(deviceAlarmLog)) {
                    deviceAlarmLog.setStatus(2);
                    deviceAlarmLog.setErrorState(2);
                    deviceAlarmLog.setRecoverTime(date);
                    deviceAlarmLogMapper.updateByPrimaryKeySelective(deviceAlarmLog);
                }
            }
            deviceLogMapper.insertSelective(deviceLog);
            deviceMapper.updateByPrimaryKeySelective(device);
            //子设备更改
//            deviceMapper.updateOnlineStatusByParentId(device.getDeviceId(), device.getOnlineStatus());

        }
        return 1;
    }

    @Override
    public int saveDeviceLog(DeviceLog deviceLog) {
        return deviceLogMapper.insertSelective(deviceLog);
    }

    @Override
    @Transactional
    public int setDeviceParamOne(DeviceParam deviceParam) {
        DeviceTypeParam checkDeviceParam = deviceTypeParamMapper.checkIdentifier(deviceParam.getIdentifier(), deviceParam.getTypeId());
        if (StringUtils.isNull(checkDeviceParam)) {
            throw new CustomException("该参数信息不存在");
        }
        //删除原来的
        deviceParamMapper.deleteByDeviceIdAndParamId(deviceParam.getDeviceId(), deviceParam.getParamId());
        Integer dataType = checkDeviceParam.getDataType();
        //1数值 ，2枚举,3字符串，4浮点数
        try {
            switch (dataType) {
                case 1:
                    Integer.parseInt(deviceParam.getValue());
                    break;
                case 4:
                    Double.parseDouble(deviceParam.getValue());
                    break;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new CustomException("参数数据格式错误，请重新填写");
        }
        return deviceParamMapper.insertSelective(deviceParam);
    }

    @Override
    @DataScope(deptAlias = "sd")
    public Integer deviceCount(SysUser user) {
        return deviceMapper.deviceCount(user);
    }

    @Override
    @DataScope(deptAlias = "sd")
    public List<Map<String, Integer>> deviceOnlineCount(SysUser user) {
        return deviceMapper.deviceOnlineCount(user);
    }

    @Override
    @DataScope(deptAlias = "sd")
    public List<Map<String, Object>> subordinateDeviceCount(SysUser user) {
        return deviceMapper.subordinateDeviceCount(user);
    }

    @Override
    @DataScope(deptAlias = "sd")
    public List<Map<String, Object>> typeDeviceCount(SysUser user) {
        return deviceMapper.typeDeviceCount(user);
    }

    @Override
    public Device selectDeviceByDeviceNum(String deviceNum, Integer addr) {
        return deviceMapper.selectByDeviceNum(deviceNum, addr);
    }

    @Override
    public int updateDeviceParam(DeviceParam deviceParam) {
        return deviceParamMapper.updateByPrimaryKey(deviceParam);
    }

    @Override
    public int insertSelective(DeviceParam deviceParam) {
        return deviceParamMapper.insertSelective(deviceParam);
    }

    @Override
    public int deleteDeviceParam(Long deviceId) {
        return deviceParamMapper.deleteByDeviceIdAndParamType(deviceId, 1);
    }

    @Override
    public int insertSelectivePastRecords(DevicePastRecords pastRecords) {
        return devicePastRecordsMapper.insertSelective(pastRecords);
    }


    @Override
    @DataScope(deptAlias = "sd")
    public List<DeviceNumBySite> selectDeviceNumBySite(DeviceNumBySite deviceNumBySite) {
        return deviceMapper.selectDeviceNumBySite(deviceNumBySite);
    }

    @Override
    public String selectHistoryDataExport(Long deviceId, Date startTime, Date endTime) {
        Device device = selectDeviceByDeviceId(deviceId);
        List<DevicePastRecordsVo> devicePastRecordsVos = devicePastRecordsMapper.selectHistoryDataTimeNotPage(deviceId, startTime, endTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<DeviceParam> headerList = new ArrayList<>();
        List<DeviceParam> deviceParams = device.getDeviceParams();
        DeviceParam param = new DeviceParam();
        param.setParamName("时间");
        String uuid = UUID.randomUUID().toString().substring(0, 6);
        param.setIdentifier("dataTime" + uuid);
        headerList.add(param);
        headerList.addAll(deviceParams);

        for (DevicePastRecordsVo devicePastRecordsVo : devicePastRecordsVos) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("dataTime" + uuid, sdf.format(devicePastRecordsVo.getTime()));
            for (DeviceParam deviceParam : deviceParams) {
                List<DevicePastRecords> data = devicePastRecordsVo.getDevicePastRecords();
                String identifier = deviceParam.getIdentifier();
                resultMap.put(identifier, "");
                for (DevicePastRecords datum : data) {
                    if (identifier.equals(datum.getIdentifier())) {
                        resultMap.put(identifier, datum.getValue());
                    }
                }
            }
            resultList.add(resultMap);
        }

        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet(device.getDeviceNum());
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headerList.size(); i++) {
            DeviceParam deviceParam = headerList.get(i);
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(deviceParam.getParamName());
            sheet.setColumnWidth(i, 5000);
        }

        for (int j = 1; j < resultList.size() + 1; j++) {
            Row row = sheet.createRow(j);
            Map<String, Object> map = resultList.get(j - 1);
            for (int i = 0; i < headerList.size(); i++) {
                DeviceParam deviceParam = headerList.get(i);
                String paramUnits = deviceParam.getParamUnits();
                String value = (String) map.get(deviceParam.getIdentifier());
                if (paramUnits != null) {
                    value = value + " " + paramUnits;
                    if (deviceParam.getDataType() == 2) {
                        JSONObject jsonObject = JSONObject.parseObject(paramUnits);
                        value = jsonObject.getString((String) map.get(deviceParam.getIdentifier()));
                    }
                }
                Cell dateCell = row.createCell(i);
                dateCell.setCellValue(value);
            }
        }
        String fileName = UUID.randomUUID().toString() + "_" + "device.xlsx";
        File file = new File(ProjectConfig.getDownloadPath() + fileName);
        try {
            FileOutputStream out = new FileOutputStream(file);
            workbook.write(out);
            workbook.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }


    @Override
    public List<ChartVo> selectParamChart(Long deviceId, Long[] paramId, Date startTime, Date endTime) {
        return devicePastRecordsMapper.selectParamChart(deviceId, paramId, startTime, endTime);
    }


    @Override
    public Device selectChildDeviceByParentIdAndAddr(Long parentId, Integer addr) {
        return deviceMapper.selectChildDeviceByParentIdAndAddr(parentId, addr);
    }


    @Override
    public List<Device> selectChildDeviceByParentId(Long deviceId) {
        return deviceMapper.selectChildDeviceByParentId(deviceId);
    }

    @Override
    public int updateChildDevice(Device device) {
        return deviceMapper.updateChildDevice(device);
    }

    @Autowired
    private WeiYuDeviceUtils weiYuDeviceUtils;

    @Override
    public int controlTurn(Long deviceId, Integer state, String weiyu_user) {
        Device device = deviceMapper.selectByPrimaryKey(deviceId);
        if (StringUtils.isNull(device)) {
            throw new CustomException("设备信息不存在");
        } else if (state != 1 && state != 0) {
            throw new CustomException("下发开关状态不正确");
        }
        String token = null;
        try {
            token = weiYuDeviceUtils.getToken(weiyu_user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("参数设置错误，请联系管理员");
        }
        if (StringUtils.isNull(token)) {
            throw new CustomException("获取token错误，请联系管理员");
        }
        /**
         * 请求接口下发信息
         */
        String url = "http://47.110.53.42:9999/v4/devices/control/" + device.getDeviceNum() + "/turn";
        Map<String, Object> params = new HashMap<>();
        params.put("state", state);
        String result = HttpUtils.sendPostJSON(url, JSONObject.toJSONString(params), token);
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (!"200".equals(code)) {
            throw new CustomException(jsonObject.getString("msg"));
        }
        return 1;
    }

    @Override
    public List<DeviceListVo> getAllDeviceList(Long deptId) {
        return deviceMapper.getAllDeviceList(deptId);
    }

    @Override
    public List<DeviceListVo> searchDeviceName(DeviceSearchDto dto) {
        return deviceMapper.searchDeviceName(dto);
    }
    @Transactional
    @Override
    public int insertDevice(DeviceInfoDto dto) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        dto.setCreateUser(loginUser.getUser().getUser_id());
        dto.setDept_id(loginUser.getUser().getDept_id());
        deviceMapper.insertDevice(dto);
        deviceMapper.insertDeviceInfo(dto.getDevice_id());
        return 1;
    }

    @Override
    public int deviceDelete(String id) {
        return deviceMapper.deviceDelete(id);
    }

    @Override
    public HashMap<String,Object> deviceDetail(String id) {
        List<DeviceDetailVo> detail = deviceMapper.deviceDetail(id);
        //List<DeviceDetailAlarmVo> alarmDetail = deviceMapper.deviceAlarmDetail(id);
       // List<DeviceAlarmCountVo> vos = deviceMapper.countDeviceAlarm(id);

        HashMap<String,Object> map =new HashMap<>();
        map.put("detail",detail);
        map.put("alarm",deviceMapper.historyData(id));
        return map;
    }

    @Override
    public List<DeviceAlarmCountVo> deviceDetailAlarmHistory(AlarmHistoryDto dto) {

        return  deviceMapper.deviceDetailAlarmHistory(dto);
    }

    @Override
    public List<DeviceGroupChildVo> deviceGroup(String id,String group_name) {
        List<DeviceGroupChildVo> list = deviceMapper.deviceGroup(id,group_name);

        for (DeviceGroupChildVo deviceGroupChildVo : list) {
            if(deviceGroupChildVo.getSon_device().size()!=0){
                for (DeviceGroupVo deviceGroupVo : deviceGroupChildVo.getSon_device()) {
                   long count = deviceGroupVo.getAlarm_time().stream().count();
                    if(count!=0){
                        deviceGroupChildVo.setDevice_alarm_count(String.valueOf(count));
                    }
                }
                deviceGroupChildVo.setDevice_count(String.valueOf(deviceGroupChildVo.getSon_device().size()));
            }
        }

        return list;
    }

    @Override
    public List<DeviceGroupVo> deviceGroupDetail(Integer id) {

        return deviceMapper.deviceGroupDetail(id);
    }

    @Override
    public int deviceGroupEdit(String group_name,String id) {
        return deviceMapper.deviceGroupEdit(group_name,id);
    }

    @Override
    public int createDeviceGroup(AddGroupDto dto) {
        return deviceMapper.createDeviceGroup(dto);
    }



    @Override
    @Transactional
    public int addToDeviceGroup(List<String> ids, String groupName) {
        AddGroupDto addGroupDto = new AddGroupDto();
        addGroupDto.setName(groupName);
        deviceMapper.createDeviceGroup(addGroupDto);
        for (String id : ids) {
            deviceMapper.addToDeviceGroup(id,addGroupDto.getId().toString());
        }
        return 1;
    }

    @Override
    public int deviceModify(Long deviceId,String deviceName,String deviceNo,String locations,String height,String low) {

        Device device = new Device();
        device.setDeviceId(deviceId);
        device.setDeviceNum(deviceNo);
        device.setDeviceName(deviceName);
        device.setLocaltion(locations);
        device.setHeight(height);
        device.setLow(low);
        deviceMapper.updateByPrimaryKeySelective(device);
        return 1;
    }

    @Override
    @Transactional
    public int deleteDeviceGroup(String group_id) {
        deviceMapper.deleteDeviceGroupId(group_id);
        deviceMapper.deleteDeviceGroup(group_id);
        return 1;
    }

    @Override
    public int deleteDeviceFromGroup(String id) {

        return deviceMapper.deleteDeviceFromGroup(id);
    }

    @Override
    public Map<String,String> deviceStatus() {

        return null;
    }

    @Override
    public List<Object> bigScreen() {
        Map<String,String> map = new HashMap<>();
        map.put("在线数量",deviceMapper.online());
        map.put("离线数量",deviceMapper.offline());

        List<Object> list = new ArrayList<>();
        list.add(map);
        list.add(deviceMapper.deviceAlarmManage(null,null,null));
        list.add(deviceMapper.deviceUseTimes());

        list.add(deviceMapper.deviceErrorAlarms());

        return list;
    }

    @Override
    public List<DeviceListVo> checkDeviceNum(String device_num) {
        return deviceMapper.checkDeviceNum(device_num);
    }

    @Override
    public int deviceToGroup(String group_id, String device_id) {
        return deviceMapper.deviceToGroup(group_id, device_id);
    }


}
